package com.psy.counseling.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psy.counseling.entity.Question;
import com.psy.counseling.utils.Result;
import com.psy.counseling.entity.Article;
import com.psy.counseling.service.ArticleService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  文章管理的增删改查和导入导出
 * </p>
 *
 * @author 陈灿
 * @since 2022-05-31
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;
    @PostMapping
    public Result<?> save(@RequestBody Article article) {
        articleService.save(article);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Article article) {
        articleService.updateById(article);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        articleService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(articleService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        List<Article> list = articleService.list();
        return Result.success(list);
    }
    @PostMapping("/importArticles")
    public Result<?> importUsers(MultipartFile multipartFile) throws IOException {
        ArrayList<Integer> errorList = articleService.importArticles(multipartFile);
        errorList.forEach(System.out::println);
        return Result.success(errorList);
    }
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<Article> all = articleService.list();
        for (Article obj : all) {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("id", obj.getId());
            row.put("发布人", obj.getTname());
            row.put("标题", obj.getTitle());
            row.put("内容", obj.getContent());
            row.put("发布时间", obj.getTime());
            list.add(row);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("文章信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String title,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Article> query = Wrappers.<Article>lambdaQuery().orderByDesc(Article::getId);
        if (StrUtil.isNotBlank(title)) {
            query.like(Article::getTitle,title);
        }
        IPage<Article> page = articleService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }

}

